/*
 * Copyright (C) 2010 The Android Open Source Project 
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at 
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and 
 * limitations under the License.
 */
package com.freeforall;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

/** 
 * Represents a single cell in the board. Synchronizes access to Piece inside.
 * @author Erik Buchholz
 * @author Mike Peterson
 */
public class Cell {

	private Piece piece;
	private int color;
	private Handler textHandler;
	
	/** Sets the initial contents of the cell to null. */
	public Cell(Handler textHandler){
		piece = null;
		color = 0xff888888;
		this.textHandler = textHandler;
	}
	
	/** Moves a piece into the cell. If there is already there, it gets eaten. */
	public synchronized void insertPiece(Piece piece){
		if (this.piece != null && !piece.getEaten()){
			piece.eat(this.piece);
			Message msg = new Message();
			Bundle b = new Bundle();
			b.putString("eatData", piece.getColorName() + " ate " + this.piece.getColorName());
			msg.setData(b);
			textHandler.sendMessage(msg);
		}
		this.piece = piece;
		color = this.piece.getColor();
		Game.CELL_GRID[this.piece.getPrevY()][this.piece.getPrevX()].removePiece();
	}
	
	/** Set a cell's piece to null. */
	private synchronized void removePiece(){
		piece = null;
		color = 0xff888888;
	}
	
	/** Accessor for color. */
	public int getColor(){
		return color;
	}
}
